package com.ashermed.cxzkxc;

import java.util.ArrayList;

import com.ashermed.cxzkxc.R;
import com.ashermed.cxzkxc.util.Util;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Blutooth_Activity extends Activity implements View.OnClickListener {

	private BluetoothAdapter mBluetoothAdapter;
	private static final int REQUEST_ENABLE_BT = 1;

	private boolean mScanning; // 是否在搜索
	private Handler mHandler;
	private ListView lv_show_items;
	Button btn_scan, btn_stop, home_case_history_three_btn_refresh,
			home_case_history_three_btn_back;
	// 60秒后停止查找搜索.
	private static final long SCAN_PERIOD = 120000;// 120000;
	TextView title_font;
	ProgressBar blu_pb;
	public SharedPreferences sharedPreferences;
	public SharedPreferences.Editor editor;
	boolean IsFirstBlutooth=false;

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		mLeDeviceListAdapter.clear();
		Log.i("jsc", "onPause()");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(IsFirstBlutooth){
			scanLeDevice(false);
		}
		
		super.onDestroy();
		Log.i("jsc", "onDestroy()");
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.blutooth_activity_main);
		Log.i("jsc", "onCreate");
		// getActionBar().setTitle(R.string.title_devices);
		mHandler = new Handler();
		blu_pb = (ProgressBar) findViewById(R.id.blu_pb);
		lv_show_items = (ListView) findViewById(R.id.lv_show_items);
		btn_scan = (Button) findViewById(R.id.btn_scan);
		btn_stop = (Button) findViewById(R.id.btn_stop);
		home_case_history_three_btn_refresh = (Button) findViewById(R.id.home_case_history_three_btn_refresh);
		home_case_history_three_btn_back = (Button) findViewById(R.id.home_case_history_three_btn_back);
		title_font = (TextView) findViewById(R.id.title_font);
		title_font.setText("蓝牙同步");
		Drawable drawable = getResources().getDrawable(R.drawable.verification_tv_tongzhi_un);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),drawable.getMinimumHeight());
		home_case_history_three_btn_refresh.setCompoundDrawables(drawable,null, null, null);
		home_case_history_three_btn_refresh.setVisibility(View.VISIBLE);
		home_case_history_three_btn_refresh.setOnClickListener(this);
		home_case_history_three_btn_back.setOnClickListener(this);
		// 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
		if (!getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT)
					.show();
			Blutooth_Activity.this.finish();
		}
		sharedPreferences = Blutooth_Activity.this.getSharedPreferences("login", MODE_PRIVATE);
		String LastAssessTime = sharedPreferences.getString("IsFirstBlutooth","0");
		Log.i("jaa", "LastAssessTime:"+LastAssessTime);
		if(LastAssessTime.equals("0")||LastAssessTime.equals("")){
			Log.i("jaa", "LastAssessTime1111111111");
			IsFirstBlutooth=true;
			editor=	sharedPreferences.edit();
			editor.putString("IsFirstBlutooth", "123").commit();
			Intent intent = new Intent(Blutooth_Activity.this,Blut_Detailed.class);	
			startActivity(intent);
			Util.ActivityExit(Blutooth_Activity.this);
			Blutooth_Activity.this.finish();
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("jsc", "onResume");
		// 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
		final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = bluetoothManager.getAdapter();

		// 检查设备上是否支持蓝牙
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, R.string.error_bluetooth_not_supported,
					Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		
		// 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableBtIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
		}

		// Initializes list view adapter. 初始化列表视图适配器。
		mLeDeviceListAdapter = new LeDeviceListAdapter();
		lv_show_items.setAdapter(mLeDeviceListAdapter);

		scanLeDevice(true);

		lv_show_items.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
				Log.i("jsc", "device.getName():"+device.getName());
				if(device.getName()!=null&&device.getName().equals("BLE-MSA")){
				
				final Intent intent = new Intent(Blutooth_Activity.this,Blutooth_Second.class);
				intent.putExtra("EXTRAS_DEVICE_NAME", device.getName());
				intent.putExtra("EXTRAS_DEVICE_ADDRESS", device.getAddress());
				scanLeDevice(false);
				Blutooth_Activity.this.finish();
				startActivity(intent);
				}else{
					Toast.makeText(Blutooth_Activity.this, "无效的选择",1).show();
				}
			}

		});

	}

	// 搜索设备
	private void scanLeDevice(final boolean enable) {
		// UUID[] a =new UUID[1];
		// a[0] =UUID.fromString("0xFFF0");//0xFFF0;
		// a[0]
		// =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//0xFFF0;

		if (enable) {
			// Stops scanning after a pre-defined scan period.10秒后停止搜索
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					mScanning = false;
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					Log.i("jsc", "stop!!");
					// invalidateOptionsMenu();
					setBlu_pb();
				}
			}, SCAN_PERIOD);

			mScanning = true;

			// mBluetoothAdapter.startLeScan(a, mLeScanCallback);
			mBluetoothAdapter.startLeScan(mLeScanCallback);
			Log.i("jsc", "start!!");
		} else {
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
			Log.i("jsc", "stop!!");
		}
		setBlu_pb();
		// invalidateOptionsMenu();
	}

	private LeDeviceListAdapter mLeDeviceListAdapter;
	// Device scan callback. 设备扫描回调
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int arg1, byte[] arg2) {
			// TODO Auto-generated method stub
			runOnUiThread(new Runnable() {
				public void run() {
//					if(device.getName().equals("BLE-MAS")){
//						
//						final Intent intent = new Intent(Blutooth_Activity.this,Blutooth_Second.class);
//						intent.putExtra("EXTRAS_DEVICE_NAME", device.getName());
//						intent.putExtra("EXTRAS_DEVICE_ADDRESS", device.getAddress());
//						scanLeDevice(false);
//						Blutooth_Activity.this.finish();
//						startActivity(intent);
//					}
					mLeDeviceListAdapter.addDevice(device);
					mLeDeviceListAdapter.notifyDataSetChanged();
				}
			});
		}
	};

	public void setBlu_pb() {
		if (!mScanning) {

			blu_pb.setVisibility(View.GONE);
		} else {

			blu_pb.setVisibility(View.VISIBLE);
		}

	}

	// Adapter for holding devices found through scanning. 通过扫描发现的保持装置的适配器。
	private class LeDeviceListAdapter extends BaseAdapter {
		private ArrayList<BluetoothDevice> mLeDevices;
		private LayoutInflater mInflator;

		public LeDeviceListAdapter() {
			super();
			mLeDevices = null;
			mLeDevices = new ArrayList<BluetoothDevice>();
			mInflator = Blutooth_Activity.this.getLayoutInflater();
		}

		public void addDevice(BluetoothDevice device) {
			Log.i("jsc", "addDevice()");
			Log.i("jsc", "addDevice:"+device.getName());
			if (!mLeDevices.contains(device)) {
				mLeDevices.add(device);
			}
		}

		public BluetoothDevice getDevice(int position) {
			return mLeDevices.get(position);
		}

		public void clear() {
			mLeDevices.clear();
		}

		@Override
		public int getCount() {
			Log.i("jsc", "size():"+mLeDevices.size());
			return mLeDevices.size();
		}

		@Override
		public Object getItem(int position) {
			return mLeDevices.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = mInflator.inflate(
						R.layout.blutooth_listitem_device, null);
				viewHolder = new ViewHolder();
				viewHolder.deviceAddress = (TextView) convertView
						.findViewById(R.id.device_address);
				viewHolder.deviceName = (TextView) convertView
						.findViewById(R.id.device_name);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			BluetoothDevice device = mLeDevices.get(position);
			final String deviceName = device.getName();
			if (deviceName != null && deviceName.length() > 0) {
				viewHolder.deviceName.setText(deviceName);
			} else {
				viewHolder.deviceName.setText(R.string.unknown_device);
			}
			viewHolder.deviceAddress.setText(device.getAddress());
			return convertView;
		}

	}

	static class ViewHolder {
		TextView deviceName;
		TextView deviceAddress;
	}

	/*
	 * @Override public boolean onCreateOptionsMenu(Menu menu) {
	 * getMenuInflater().inflate(R.menu.main, menu); Log.i("jsc", "msg"); if
	 * (!mScanning) { menu.findItem(R.id.menu_refresh).setActionView(null); }
	 * else {
	 * 
	 * menu.findItem(R.id.menu_refresh).setActionView(
	 * R.layout.blutooth_actionbar_indeterminate_progress); } return true; }
	 */
	

	@Override
	public void onClick(View v) {

		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.home_case_history_three_btn_refresh:
			Intent intent = new Intent(Blutooth_Activity.this,Blut_Detailed.class);
			Blutooth_Activity.this.finish();
			Blutooth_Activity.this.startActivity(intent);
			break;

		case R.id.home_case_history_three_btn_back:
//			Intent i = new Intent(Blutooth_Activity.this,
//					CaseHistoryThreeInfoActivity.class);
//			BaseActivity.flag="1";
//			BaseActivity.boolIsLoadData=true;
//			i.putExtra("ICON_CLICK", "C");
//			startActivity(i);
			Util.ActivityExit(Blutooth_Activity.this);
			Blutooth_Activity.this.finish();
			break;

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		Intent i = new Intent(Blutooth_Activity.this,
//				CaseHistoryThreeInfoActivity.class);
//		BaseActivity.flag="1";
//		BaseActivity.boolIsLoadData=true;
//		i.putExtra("ICON_CLICK", "C");
//		startActivity(i);
		Util.ActivityExit(Blutooth_Activity.this);
		Blutooth_Activity.this.finish();
		return super.onKeyDown(keyCode, event);
	}

}
